#include "qparamdb.h"
#include "QtSql/QSqlDatabase"
#include <QDebug>

QParamDB::QParamDB(QObject *parent) : QObject(parent)
{
    DB = QSqlDatabase::addDatabase("QSQLITE");
    DB.setDatabaseName("Regexp.db");

    if (!DB.open()){
        qDebug() << DB.lastError().text();
    }
}

QParamDB::~QParamDB()
{
    DB.close();
}

QString QParamDB::GetValueByName(const QString &name)
{
    QSqlDatabase tempDB(DB);

    QString str = "SELECT Pattern FROM RegexpList WHERE Name='%1';";
    str = str.arg(name);

    QSqlQuery tempQuery = QSqlQuery(tempDB);


    if (!tempQuery.exec(str)){
        qDebug() << tempQuery.lastError();
        return "";
    }
    qDebug() << tempQuery.record().value(0);

    return tempQuery.record().value(0).toString();
}

void QParamDB::InsertNewParam(const QString &name, const QString &value)
{
    QString str = "INSERT INTO RegexpList (Name, Pattern) VALUES ('%1','%2');";
    str = str.arg(name, value);

    QSqlQuery tempQuery = QSqlQuery(DB);

    if (!tempQuery.exec(str)){
        qDebug() << tempQuery.lastError();
    }
}

void QParamDB::RemoveParam(const QString &name)
{
    QString str = "DELETE FROM RegexpList WHERE Name='%1'";
    str = str.arg(name);

    QSqlQuery tempQuery = QSqlQuery(DB);

    if (!tempQuery.exec(str)){
        qDebug()  << tempQuery.lastError();
    }
}

QString QParamDB::getNames()
{
    QString str = "SELECT Name FROM RegexpList";
    QSqlQuery tempQuery = QSqlQuery(DB);

    if (!tempQuery.exec(str)){
        qDebug() << tempQuery.lastError();
        return "";
    }
    QStringList sl;
    while(tempQuery.next()){
        sl.append(tempQuery.record().value(0).toString());
    }
    return sl.join(",");
}


